package cn.ichiva.puppet.example.base.p2;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.impl.AbstractPuppetComponent;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.util.*;

public class TodoManager extends AbstractPuppetComponent {

    @FXML
    StringProperty inTodo = new SimpleStringProperty();

    @FXML
    List<Todo> list = new ArrayList<>(Arrays.asList(
            new Todo("盘古MES二开"),
            new Todo("用友NC会议"),
            new Todo("泛微OA技术支持")
    ));

    @Override
    public CharSequence render() {
        imports(VBox.class,HBox.class,TextField.class,Button.class, TodoList.class);
        return """
                <VBox>
                    <HBox>
                        <TextField text="${inTodo}" onKeyPressed="#insertTodo"/>
                        <Button text="#${添加}" onAction="#addTodo" />
                    </HBox>
                    <TodoList props="list,#removeTodo" />
                </VBox>
                """;
    }



    @FXML
    void removeTodo(int index){
        list.remove(index);
        update();
    }

    @FXML
    void insertTodo(KeyEvent event){
        if (event.getCode() == KeyCode.ENTER) {
            addTodo(event);
        }
    }

    @FXML
    void addTodo(Event event){
        String text = inTodo.get();
        if(text != null && text.length() != 0){
            Todo todo = new Todo();
            list.add(todo);

            todo.setText(text);
            todo.setCreateTime(new Date());
            inTodo.set("");
            update();
        }
    }
}
